<?php

/**
 *
 * @author ben <ben@spicatech.cn>  Created on 2015-6-27
 */
class ProjectActiveRecord extends CActiveRecord {

    public function beforeSave() {
        $now = date('Y-m-d H:i:s');
        if (parent::beforeSave()) {
            if ($this->isNewRecord && $this->hasAttribute('create_time')) {
                $this->create_time = $now;
            }
            if ($this->hasAttribute('update_time')) {
                $this->update_time = $now;
            }
            return true;
        }
        return false;
    }

    /**
     * 获取第一个错误字段的提示文字
     * @return string
     */
    public function getFirstErrorDesc() {
        $errors = $this->getErrors();
        if (empty($errors)) {
            return '';
        }
        foreach ($errors as $attr => $error) {
            return $this->getErrorDesc($attr, $error);
        }
    }

    /**
     * 获取错误字段的提示文字
     * @param type $attr
     * @param array $error
     * @return string
     */
    public function getErrorDesc($attr, array $error) {
        $labels = $this->attributeLabels();
        $name = isset($labels[$attr]) ? $labels[$attr] : '';
        $errorMsg = implode('、', $error);
        if (strpos($errorMsg, $name) === 0) {
            $name = '';
        }
        $errmsg = $name . $errorMsg;
        return $errmsg;
    }

    /**
     * 
     * @return array
     */
    public function modelToArray() {
        return $this->getAttributes();
    }

    /**
     * 
     * @param array $modelList
     * @return array
     */
    public function modelListToAssocArray($modelList) {
        $res = array();
        foreach ($modelList as $model) {
            if (!is_a($model, 'CActiveRecord')) {
                continue;
            }
            $res[] = $model->modelToArray();
        }
        return $res;
    }

}
